<script setup lang="ts">
import dayjs from 'dayjs'
import { useLoadMore } from 'vue-request'
import { fetchCouponListAPI } from '@/apis/fetchCouponList'
import dialogIcon from '@/static/images/checkmark_colorful.png'
import { useUserInfoStore } from '@/store/userInfo'
import { claimCouponAPI } from '@/apis/claimCoupon'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, mutate } = useLoadMore<LoadMoreData<Coupon>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onReachBottom(() => loadMore())

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<Coupon>): Promise<LoadMoreData<Coupon>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchCouponListAPI(
    { page: _page.toString(), limit: '10' },
    userInfoStore.userInfo!.token!,
  )

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

const isShowDialog = ref(false)

const handleClaimCoupon = useThrottleFn(async (id: string) => {
  try {
    const res = await claimCouponAPI({ id }, userInfoStore.userInfo!.token!)
    if (res.data?.code === 1) {
      isShowDialog.value = true
      mutate((oldData) => {
        return {
          ...oldData,
          list: oldData.list.filter(i => i.id.toString() !== id),
        }
      })
    }
    else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
})

function handleViewMyCoupon() {
  router.replace({
    name: 'myCouponList',
  })
}
</script>

<template>
  <view class="min-h-screen bg-#F8F8F8">
    <Spacer height="40" />
    <view v-if="dataList.length > 0" class="px-24rpx">
      <CouponItem
        v-for="item in dataList"
        :id="item.id.toString()"
        :key="item.id"
        :name="item.name"
        :price="item.complete_money"
        :discount-rate="item.discount.toString()"
        :type="item.type"
        :minisum="item.money"
        :classificate="item.classificate"
        :period="{
          start: dayjs.unix(item.use_start_time!).format('YYYY.MM.DD'),
          end: dayjs.unix(item.use_end_time!).format('YYYY.MM.DD'),
        }"
        :tip="item.explain"
        :owned="false"
        @claim="handleClaimCoupon(item.id.toString())"
      />
      <!-- 加载更多 -->
      <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
      <Spacer height="240" />
    </view>
    <PageDefault v-else>
      暂无优惠券
    </PageDefault>
  </view>
  <button
    class="fixed bottom-0 z-2 h-128rpx w-screen flex items-center justify-center rounded-0 bg-#4999F7 text-32rpx text-white leading-45rpx x-center"
    @tap="handleViewMyCoupon"
  >
    <image class="h-30rpx w-44rpx" src="@/static/images/coupon_single_color.png" />
    <Spacer width="16" />
    我的优惠券
  </button>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
  <uv-overlay :show="isShowDialog" @tap="isShowDialog = false">
    <uv-transition mode="zoom-in" :show="isShowDialog">
      <view class="relative h-screen w-screen">
        <Dialog
          :icon="dialogIcon"
          title="领取成功"
          content="优惠券领取成功，请前往我的优惠券进行使用"
          confirm-label="去使用"
          @cancel="isShowDialog = false"
          @confirm="handleViewMyCoupon"
        />
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'couponList'
style:
  navigationBarTitleText: '领券中心'
layout: 'custom'
</route>
